<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/5
 * Time: 9:39
 */

namespace app\index\controller;

use app\index\model\ChongzhiList;
use app\common\controller\PayBase;
use think\Db;

class Paysyf extends PayBase{

    private $merNo;         //商户号
    private $subMerNo;      //子商户号
    private $key;           //
    private $callBackUrl;
    private $callBackViewUrl;
    public function __construct(){
        parent::__construct();
        $this->merNo = 'SYF201805020800';
        $this->subMerNo = 'SYF201805020800';
        $this->key = '289EBC7E9E3C1356BCA263AC44F9F879';
        $this->callBackUrl = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/index/Paysyf/payReturn';
        $this->callBackViewUrl = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/index/Paysyf/payReturnView';
    }
    /**
     * 闪忆付上行支付接口
     */
    public function initPay($username='',$pay_type='',$amount=-1,$from=0){
        //接收数据

        $user = cookie('username','');
        $password = cookie('password','');
        $username =  empty($username) ? input('post.username','') : $username;
        $bank_code = empty($pay_type) ? input('post.pay_type','') : $pay_type;
        $amount = -1==$amount ? input('post.amount',0) : $amount;

        $ctime = time();
        if($bank_code=='null' || $bank_code=='') return packJson('','请选择支付方式',500);
        $pay_method = Db::name('pay_type_list')
            ->alias("a")
            ->join('__PAY_METHOD__ b','a.method_id=b.id','LEFT')
            ->where(['a.method'=>7,'a.type_value'=>$bank_code])
            ->field('a.type_name,b.name,b.id,b.method,b.money')->find();
        $remark = $pay_method['type_name'].'-'.$pay_method['name'];
        //验证用户信息
        if( 0==$from ){
            if(!$user || !$username || ($user!=$username)) return packJson('','用户身份验证失败',500);
            $user_info = Db::name('username')->field('id,us_class,swzh,nbzh')->where(['username'=>$username,'password'=>$password])->find();
        }else{
            $user_info = Db::name('username')->field('id,us_class,swzh,nbzh')->where(['username'=>$username])->find();
        }

        if(!$user_info) return packJson('','用户身份验证失败',500);
        if($user_info['swzh'] == 1) return packJson('','试玩账号无法充值',500);
        if($user_info['nbzh'] == 1) return packJson('','内部账号不支持线上充值',500);

        //充值防骚扰是否开启，并进行处理
        $harassment = Db::name('xt_czfsr')->find();
        if($harassment['open'] > 0) {
            $nowys = $ctime - $harassment['time_xs'] * 60;
            $old_czjl = Db::name('chongzhi_list')->where('username',$username)->where('cztime','>',$nowys)->find();
            if($old_czjl['id'] > 0) {
                return packJson('',"系统充值防骚扰已开启，{$harassment['time_xs']}分钟内只能充值1次！",500);
            }
        }

        //验证金额
        if($amount <= 0) return packJson('','请输入充值金额',500);
        if($amount < 50) return packJson('','最低充值金额为五十元人民币',500);
        if($amount > 20000) return packJson('','充值金额超过范围',500);

        //计算优惠金额
        $msje = $msbs = 0;
        $cz_set = Db::name('xt_chongzhi')->find();
        $user_class = Db::name('us_class')->where('id',$user_info['us_class'])->find();
        $zsje = $amount * $user_class['czzsbl'] / 100;
        $zsbs = $user_class['czzsbl'];
        if($amount >= $cz_set['xscz_je']) {
            $msje = $amount * $cz_set['xscz_zs'] / 100;
            $msbs = $cz_set['xscz_zs'];
        }
        //充值方案赠送
        $method_money = 0.00;
        if( floatval( $pay_method['money'] ) > 0 ){
            if( 0==intval( $pay_method['method'] ) ){
                //金额
                $method_money = $pay_method['money'];
            }else{
                //比例
                $method_money = floatval($amount) * floatval($pay_method['money']) / 100;
            }
        }
        $method_money = sprintf("%.2f",substr(sprintf("%.3f", $method_money), 0, -2));

        //生成订单号
        $order_sn = 'SYF' . str_pad($user_info['id'],5,'0',STR_PAD_LEFT) . $ctime . rand(111,999);

        //处理数据并生成签名
        if( 1==$from ) $this->callBackViewUrl.="Third";
        $Rsa = new Rsa();
        $data['orderNum'] = $order_sn;
        $data['version'] = 'V4.0.0.0';
        $data['charset'] = 'UTF-8';
        $data['random'] = (string) rand(1000,9999);
        $data['merNo'] = $this->merNo;
        $data['subMerNo'] = $this->subMerNo;
        $data['netway'] = $bank_code;
        $data['amount'] = strval($amount*100);	// 单位:分
        $data['goodsName'] = '闪亿付在线充值';
        $data['callBackUrl'] = $this->callBackUrl;
        $data['callBackViewUrl'] = $this->callBackViewUrl;
        $data['sign'] = create_sign($data,$this->key);
        $json = json_encode_ex($data);
        $dataStr = $Rsa->encode_pay($json);
        $param = 'data=' . urlencode($dataStr) . '&merchNo=' . $this->merNo . '&version=V4.0.0.0';
        $result = wx_post(config('PAY_URL')[$bank_code],$param);
        $rows = json_to_array($result,$this->key);
        if( '00'==$rows['stateCode'] ){
            //插入充值信息
        	$u = Db::name('username')->where('username',$username)->value('je');
            $model = new ChongzhiList();
            if( $model->setTransRechargeInfo($order_sn,$amount,$username,0,0,1,$remark,$ctime,'闪忆付线上支付','系统自动',get_ip(),0,$bank_code,$zsje,$zsbs,$msje,$msbs,$user_info['us_class'],'',0,$method_money,$u) ){
                return packJson($rows['qrcodeUrl'],'',200);
            }else{
                return packJson('',"订单生产错误",500);
            }
        }else{
            return packJson('',$rows['msg'],500);
        }
    }
    public function payReturn(){
        file_put_contents('syf_return.txt',var_export(input(),true).PHP_EOL,FILE_APPEND);
    }
    public function payReturnView(){
        file_put_contents('syf_view.txt',var_export(input(),true).PHP_EOL,FILE_APPEND);
    }
    public function payReturnViewThird(){
        file_put_contents('syf_view.txt',var_export(input(),true).PHP_EOL,FILE_APPEND);
    }
}

class Rsa{
    private $pay_public_key;
    private $remit_public_key;
    private $private_key;

    public function __construct($key = null){
        $this->private_key = "-----BEGIN RSA PRIVATE KEY-----\r\n";
        foreach (str_split(config('SYF_PRIVATE_KEY'),64) as $str){
            $this->private_key = $this->private_key . $str . "\r\n";
        }
        $this->private_key = $this->private_key . "-----END RSA PRIVATE KEY-----";

        $this->pay_public_key = "-----BEGIN PUBLIC KEY-----\r\n";
        foreach (str_split(config('SYF_PAY_PUBLIC_KEY'),64) as $str){
            $this->pay_public_key = $this->pay_public_key . $str . "\r\n";
        }
        $this->pay_public_key = $this->pay_public_key . "-----END PUBLIC KEY-----";
        $this->remit_public_key = "-----BEGIN PUBLIC KEY-----\r\n";
        foreach (str_split(config('SYF_REMIT_PUBLIC_KEY'),64) as $str){
            $this->remit_public_key = $this->remit_public_key . $str . "\r\n";
        }
        $this->remit_public_key = $this->remit_public_key . "-----END PUBLIC KEY-----";
    }
    public function encode_pay($data){#加密
        $pu_key = openssl_pkey_get_public($this->pay_public_key);
        if ($pu_key == false){
            echo "打开密钥出错";
            die;
        }
        $encryptData = '';
        $crypto = '';
        foreach (str_split($data, 117) as $chunk) {
            openssl_public_encrypt($chunk, $encryptData, $pu_key);
            $crypto = $crypto . $encryptData;
        }

        $crypto = base64_encode($crypto);
        return $crypto;

    }


    public function encode_remit($data){#加密
        $pu_key = openssl_pkey_get_public($this->remit_public_key);
        if ($pu_key == false){
            echo "打开密钥出错";
            die;
        }
        $encryptData = '';
        $crypto = '';
        foreach (str_split($data, 117) as $chunk) {
            openssl_public_encrypt($chunk, $encryptData, $pu_key);
            $crypto = $crypto . $encryptData;
        }

        $crypto = base64_encode($crypto);
        return $crypto;

    }

    public function decode($data){
        $pr_key = openssl_get_privatekey($this->private_key);
        if ($pr_key == false){
            echo "打开密钥出错";
            die;
        }
        $data = base64_decode($data);
        $crypto = '';
        foreach (str_split($data, 128) as $chunk) {
            openssl_private_decrypt($chunk, $decryptData, $pr_key);
            $crypto .= $decryptData;
        }
        return $crypto;
    }


}

function wx_post($url,$data){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $tmpInfo = curl_exec($ch);
    if (curl_errno($ch)) {
        return curl_error($ch);
    }
    return $tmpInfo;

}
function json_encode_ex($value){
    if (version_compare(PHP_VERSION,'5.4.0','<')){
        $str = json_encode($value);
        $str = preg_replace_callback("#\\\u([0-9a-f]{4})#i","replace_unicode_escape_sequence",$str);
        $str = stripslashes($str);
        return $str;
    }else{
        return json_encode($value,320);
    }
}
function json_decode_ex($value){
    return json_decode($value,true);
}

function replace_unicode_escape_sequence($match) {
    return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
}

function create_sign($data,$key){
    ksort($data);
    $sign = strtoupper(md5(json_encode_ex($data) . $key));
    return $sign;
}

function json_to_array($json,$key){
    $array = json_decode_ex($json);
    if ($array['stateCode'] == '00'){
        $sign_string = $array['sign'];
        ksort($array);
        $sign_array = array();
        foreach ($array as $k => $v) {
            if ($k !== 'sign'){
                $sign_array[$k] = $v;
            }
        }
        $md5 =  strtoupper(md5(json_encode_ex($sign_array) . $key));
        if ($md5 == $sign_string){
            return $sign_array;
        }else{
            $result = array();
            $result['stateCode'] = '99';
            $result['msg'] = '返回签名验证失败';
            return $result;
        }
    }else{
        $result = array();
        $result['stateCode'] = $array['stateCode'];
        $result['msg'] = $array['msg'];
        return $result;
    }
}
function callback_to_array($json,$key){
    $array = json_decode_ex($json);
    $sign_string = $array['sign'];
    ksort($array);
    $sign_array = array();
    foreach ($array as $k => $v) {
        if ($k !== 'sign'){
            $sign_array[$k] = $v;
        }
    }
    $md5 =  strtoupper(md5(json_encode_ex($sign_array) . $key));
    if ($md5 == $sign_string){
        return $sign_array;
    }else{
        $result = array();
        $result['payResult'] = '99';
        $result['msg'] = '返回签名验证失败';
        return $result;
    }
}